/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package term_project;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

/**
 *
 * @author Ross
 */
public class MainWindow extends JFrame 
{
    private ComputerUser user;                                                  // The logged in user
        
    private JList friendList;                                                   // Friend list
    private DefaultListModel friendModel;                                       // Friend Model
    private JScrollPane scrollFriendList;                                       // Scroll panel for the friendlist
    
    private JList chatList;                                                     // List of current chats
    private DefaultListModel chatModel;                                         // Model for the list
    private JScrollPane scrollChatList;                                        // Scroll panel for the chat list
    
    private GridBagLayout layout;                                                // Layout
    private GridBagConstraints c;                                                // Constraints
    
    private JButton openChat;                                                     // Open chat button
    private JButton removeChat;                                                   // Removes chat
    private JButton newChat;                                                      // New Chat button
    private JPanel chatHolder;                                                    // Chat panel
    private JButton whisperButton;                                              // Sends a "whisper," private message, to a user
    private JButton addFriendButton;
    
    private JLabel friendLabel;                                                   // Label for friend list
    private JLabel chatLabel;                                                     // Label for chat list
    
    ChatWindow chatWindow;                                                      // This is where our chats will be displayed.
    
    public MainWindow(ComputerUser User)
    {
        super("Talks");
        user = User;
        initComponents();
        loadLists();
    }
    // *****************************
    // * Intializing functions     *
    // *****************************
    public void initComponents()
    // PRE:  To be run in the constructor
    // POST: Will set up the window
    {
        
        // *******************************
        // * Setting up the labels       *
        // *******************************
        chatLabel = new JLabel("Active Chats");
        friendLabel = new JLabel("Friend Lists");
        friendLabel.setVerticalTextPosition(JLabel.BOTTOM);
        
        
        // ***************************
        // * Set up chat buttons     *
        // ***************************
        
        // Open a chat
        chatHolder = new JPanel();
        
        // Open a chat
        openChat = new JButton();                                               // Instantiate the button
        openChat.setMaximumSize(new Dimension(40,40));                          // Set the max size
        openChat.setMinimumSize(new Dimension(40,40));                          // Set the min size
        openChat.setPreferredSize(new Dimension(40,40));                        // Set the preferred size
        openChat.setToolTipText("Open Chat");                                   // Sets the text when the mouse hovers
        openChat.addActionListener(new ActionListener(){                        // Sets up the action listener
                                                    @Override
                                                    public void actionPerformed(ActionEvent e)
                                                    {
                                                        openButtonPressed();    // When the button pressed it will do this function
                                                    }
                                                    });
        removeChat = new JButton();                                             // Instantiate the remove chat button
        removeChat.setMaximumSize(new Dimension(40,40));                        // Set the max size
        removeChat.setMinimumSize(new Dimension(40,40));                        // Set the min size
        removeChat.setPreferredSize(new Dimension(40,40));                      // Set the preferred size
        removeChat.setToolTipText("Remove Chat");                               // Sets the hover text
        removeChat.addActionListener(new ActionListener(){                      // Sets the action for when it is clicked
                                                    @Override
                                                    public void actionPerformed(ActionEvent e)
                                                    {
                                                        removeButtonPressed();  // Performs this action when clicked
                                                    }
                                                    });
        newChat = new JButton();                                                // Instantiates the the new chat button
        newChat.setMaximumSize(new Dimension(40,40));                           // Sets the max size
        newChat.setMinimumSize(new Dimension(40,40));                           // Sets the min size
        newChat.setPreferredSize(new Dimension(40,40));                         // Sets preferred size
        newChat.setToolTipText("New Chat");                                     // Sets the hover text for the button
        newChat.addActionListener(new ActionListener(){                         // Sets the action on clicked
                                                    @Override
                                                    public void actionPerformed(ActionEvent e)
                             {
                                                        addChatButtonPressed(); // Adds the action for a new chat
                                                    }
                                                    });
        whisperButton = new JButton();
        whisperButton.setToolTipText("Send a whisper to user");
        whisperButton.setMinimumSize(new Dimension(40,40));
        whisperButton.setMaximumSize(new Dimension(40,40));
        whisperButton.setPreferredSize(new Dimension(40,40));
        whisperButton.addActionListener(new ActionListener() 
                                                            {
                                                               @Override
                                                               public void actionPerformed(ActionEvent e)
                                                               {
                                                                   whisperPressed();
                                                               }
                                                            });
        addFriendButton = new JButton();
        addFriendButton.setToolTipText("Add selected user as friend");
        addFriendButton.setMinimumSize(new Dimension(40,40));
        addFriendButton.setMaximumSize(new Dimension(40,40));
        addFriendButton.setPreferredSize(new Dimension(40,40));
        addFriendButton.addActionListener(new ActionListener() 
                                                            {
                                                                @Override
                                                               public void actionPerformed(ActionEvent e)
                                                               {
                                                                   addFriendPressed();
                                                               }
                                                            });
        
        try
       {
        Image img = ImageIO.read(this.getClass().getResource("open1.png"));     // Opens the button image
        openChat.setIcon(new ImageIcon(img));                                   // Sets the open image to the button
        img = ImageIO.read(this.getClass().getResource("remove.png"));          
        removeChat.setIcon(new ImageIcon(img));
        img = ImageIO.read(this.getClass().getResource("new.png"));
        newChat.setIcon(new ImageIcon(img));
        img = ImageIO.read(this.getClass().getResource("whisper.png"));
        whisperButton.setIcon(new ImageIcon(img));
        img = ImageIO.read(this.getClass().getResource("addFriend.png"));
        addFriendButton.setIcon(new ImageIcon(img));
       }
       catch(IOException e)
       {
           System.out.printf("Error: %s", e.toString());
       }
        chatHolder.add(openChat);
        chatHolder.add(removeChat);
        chatHolder.add(newChat);
        chatHolder.add(whisperButton);
        chatHolder.add(addFriendButton);

        // *******************************
        // * Setting up the friends list *
        // *******************************
        friendModel = new DefaultListModel();                                   // Creates the friend model
        friendList = new JList(friendModel);                                    // Creates a list with the friend model
        friendList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);       // allows the user to only select one item
        friendList.setLayoutOrientation(JList.VERTICAL);
        friendList.setVisibleRowCount(-1);                                      // Still don't know
        scrollFriendList = new JScrollPane(friendList);                         // Scroll panel for the friends list
        
        
        // ********************************
        // * Setting up the chat list     *
        // ********************************
        chatModel = new DefaultListModel();                                     // Creates the friend model
        chatList = new JList(chatModel);                                        // Creates a list with the friend model
        chatList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);         // allows the user to only select one item
        chatList.setLayoutOrientation(JList.VERTICAL);                     // Set the wrap to vertical
        chatList.setVisibleRowCount(-1);                                        // Still don't know
        scrollChatList = new JScrollPane(chatList);
        
        // ********************************
        // * Formatting the layout        *
        // ********************************
        c = new GridBagConstraints();
        layout = new GridBagLayout();
        this.setLayout(layout);
        
        c.gridx = 0;
        c.gridy = 0;
        c.insets = new Insets(5,5,0,0);
        this.add(friendLabel, c);
        
        c.weightx = .5;
        c.insets = new Insets(5,0,0,0);
        c.gridx = 3;
        c.anchor = GridBagConstraints.LINE_START;
        this.add(chatLabel, c);
        
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(5,5,0,0);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 3;
        c.gridheight = 3;
        c.weightx = .5;
        c.weighty = 1;
        this.add(scrollFriendList, c);
        
        c.insets = new Insets(5,5,0,5);
        c.gridx = 3;
        c.weightx = .5;
        c.gridwidth = 3;
        c.gridheight = 3;
        this.add(scrollChatList, c);
        
        c.fill = GridBagConstraints.NONE;
        c.anchor = GridBagConstraints.PAGE_START;
        c.gridx = 0;
        c.gridy = 5;
        c.weightx = 1;
        c.weighty = 0;
        c.gridwidth = 8;
        c.insets = new Insets(1,1,1,1);
        this.add(chatHolder, c);
       
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setMinimumSize(new Dimension(400,200));
        this.setVisible(true);
        
        chatWindow = new ChatWindow(user, this);
    }
    
    public void loadLists()
    {
        friendModel.clear();
        chatModel.clear();
        for(User users : user.getFriendsList())
        {
            friendModel.addElement(users.username);
        }
        for(Chat chats : user.getChatList())
        {
            chatModel.addElement(chats.getUsername());
        }
    }
    
    
    // ***********************
    // * Event Handlers      *
    // ***********************
    private void addChatButtonPressed()
    {
        Chat newChat;                                                           // Creates a new chat variable
        String answer;
        answer = (String)JOptionPane.showInputDialog(this,"Input chat title", "Chat Title", JOptionPane.OK_CANCEL_OPTION);
        if(answer!=null)
        {
            newChat = Chat.newChat(answer);                                     // Instantiates the new chat
            addChat(newChat);                                                   // Adds the chat
        }
    }
    public void addChat(Chat chat)
    {
        user.addChat(chat);                                                     // Adds the chat to the users list
        loadLists();                                                            // Reloads the chat list
    }
    private void removeButtonPressed()
    {
        if(chatList.getSelectedIndex() == -1 )
        {
            System.out.println("Please select a chat");
        }
        else
        {
            chatWindow.removeChat(user.getChat(chatList.getSelectedIndex()));
            
        }
        
    }
    private void openButtonPressed()
    {
        if(chatList.getSelectedIndex() == -1 )
        {
            System.out.println("Please select a chat");
        }
        else
        {
            chatWindow.addChat(user.getChat(chatList.getSelectedIndex()));
            chatWindow.setVisible(true);
        }
    }
    private void whisperPressed()
    {
        Chat newChat;                                                           // Temporary chat object
        String answer;                                                          // The users input from the dialog box
        User friend;                                                            // Friend to add to the whisper
        answer = (String)JOptionPane.showInputDialog(this,"Input whisper title", "Chat Title", JOptionPane.OK_CANCEL_OPTION);
        if(answer != null && friendList.getSelectedIndex() != 1)
        {
            friend = user.getFriend(friendList.getSelectedIndex());          // Gets the user from the chat list
            System.out.println(friend.username);                                // Error checking
            if(friend != null)      
            {
                newChat = Chat.newChat(answer);                                 // Creates the private chat
                newChat.clearUsers();                                           // clears the fake users
                newChat.addUser(user);                                          // Adds logged in user
                newChat.addUser(friend);                                        // Adds the desired person to chat with
                user.addChat(newChat);                                          // Adds the chat to the tabbed panel
                loadLists();                                                    // Refreshes all the lists
            }
        }
    }
    private void addFriendPressed()
    {
        User newFriend;
        String username;
        username = (String)JOptionPane.showInputDialog(this,"Enter the username", "Username", JOptionPane.OK_CANCEL_OPTION);
        if(username != null)
        {
            if(user.getFriend(username) == null)
            {
                newFriend = new User(username);
                user.addFriend(newFriend);
                loadLists();
            }
            else
            {
                JOptionPane.showMessageDialog(this, "This user is already on your friends list", "ERROR!", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
}